<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品名称" prop="goodsName">
        <el-input v-model="queryParams.goodsName" placeholder="请输入商品名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="商品价格" prop="price" style="width: 250px">
        <el-input v-model="queryParams.price" placeholder="请输入商品价格" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="商品描述" prop="description">
        <el-input v-model="queryParams.description" placeholder="请输入商品描述" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <!--      <el-form-item label="商户id" prop="userId">
        <el-input v-model="queryParams.userId" placeholder="请输入商户id" clearable @keyup.enter="handleQuery" />
      </el-form-item>-->
      <el-form-item label="商户名称" prop="username">
        <el-input v-model="queryParams.username" placeholder="请输入商户名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="联系信息" prop="information">
        <el-input v-model="queryParams.information" placeholder="请输入联系信息" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <!-- <el-form-item label="分类id" prop="classId">
        <el-input v-model="queryParams.classId" placeholder="请输入分类id" clearable @keyup.enter="handleQuery" />
      </el-form-item> -->

      <el-form-item label="分类" prop="classId" style="width: 250px">
        <el-select v-model="queryParams.classId" placeholder="请选择分类" @change="handleQuery">
          <el-option v-for="item in goodsType" :label=item.className :value="item.classId" />
        </el-select>
      </el-form-item>

      <el-form-item label="库存" prop="store">
        <el-input v-model="queryParams.store" placeholder="请输入库存" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="销量" prop="sales">
        <el-input v-model="queryParams.sales" placeholder="请输入销量" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="浏览量" prop="views">
        <el-input v-model="queryParams.views" placeholder="请输入浏览量" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="状态" prop="status" style="width: 250px;">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable @change="handleQuery">
          <el-option v-for="dict in sys_shop_status" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="时间范围" style="width: 308px">
        <el-date-picker v-model="dateRange" value-format="YYYY-MM-DD" type="daterange" range-separator="-"
          start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['goods:goods:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['goods:goods:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['goods:goods:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['goods:goods:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="goodsList" @selection-change="handleSelectionChange" stripe>
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="商品编号" align="center" prop="goodsId" />
      <el-table-column label="商品名称" align="center" prop="goodsName" show-overflow-tooltip />
      <el-table-column label="商品图片" align="center" prop="images" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.images" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="商品价格" align="center" prop="price" show-overflow-tooltip>
        <template #default="scope">
          {{ scope.row.price !== null && scope.row.price !== undefined ? scope.row.price.toFixed(2) + ' ￥' : '' }}
        </template>
      </el-table-column>

      <el-table-column label="商品描述" align="center" prop="description" show-overflow-tooltip />

      <el-table-column label="商户编号" align="center" prop="userId" />
      <el-table-column label="商户" align="center" prop="username" show-overflow-tooltip />
      <el-table-column label="联系信息" align="center" prop="information" show-overflow-tooltip />
      <el-table-column label="分类" align="center" prop="goodsType" />
      <el-table-column label="库存" align="center" prop="store" />
      <el-table-column label="销量" align="center" prop="sales" />
      <el-table-column label="浏览量" align="center" prop="views" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="sys_shop_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="发布时间" align="center" width="120" prop="createTime" show-overflow-tooltip>
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" width="120" prop="updateTime" show-overflow-tooltip>
        <template #default="scope">
          <span v-if="scope.row?.updateTime && scope.row.updateTime.trim() !== ''">
            {{ parseTime(scope.row.updateTime, '{y}-{m}-{d} {h}:{i}:{s}') }}
          </span>
          <span v-else>
            未更新
          </span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['goods:goods:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['goods:goods:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改商品对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="goodsRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="商品名称" prop="goodsName">
          <el-input v-model="form.goodsName" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品图片" prop="images">
          <image-upload v-model="form.images" />
        </el-form-item>
        <el-form-item label="商品价格" prop="price">
          <el-input v-model="form.price" placeholder="请输入商品价格" />
        </el-form-item>
        <el-form-item label="商品描述" prop="description">
          <el-input type="textarea" :rows="3" v-model="form.description" placeholder="请输入商品描述" />
        </el-form-item>
        <el-form-item label="商户id" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入商户id" @blur="exit" />
        </el-form-item>
        <el-form-item label="联系信息" prop="information">
          <el-input type="textarea" :rows="2" v-model="form.information" placeholder="请输入自定义联系信息" />
        </el-form-item>

        <!-- <el-form-item label="分类id" prop="classId">
          <el-input v-model="form.classId" placeholder="请输入分类id" />
        </el-form-item> -->
        <el-form-item label="分类" prop="classId">
          <el-select v-model="form.classId" placeholder="请选择分类">
            <el-option v-for="item in goodsType" :label=item.className :value="item.classId" />
          </el-select>
        </el-form-item>

        <el-form-item label="库存" prop="store">
          <el-input v-model="form.store" placeholder="请输入库存" />
        </el-form-item>
        <el-form-item label="销量" prop="sales">
          <el-input v-model="form.sales" placeholder="请输入销量" />
        </el-form-item>
        <el-form-item label="浏览量" prop="views">
          <el-input v-model="form.views" placeholder="请输入浏览量" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in sys_shop_status" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm" :disabled="!form.userId || !form.goodsName || !form.price">确
            定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Goods">
import { listGoods, getGoods, delGoods, addGoods, updateGoods } from "@/api/goods/goods"
import { reactive, onMounted } from "vue"
import { listTclassify } from "../../../api/tclassify/tclassify"
import { parseTime } from "@/utils/ruoyi.js";
import { getUsers } from "../../../api/users/users"
const { proxy } = getCurrentInstance()
const { sys_shop_status } = proxy.useDict('sys_shop_status')

const goodsList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

//日期范围
const dateRange = ref([])

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    goodsName: null,
    images: null,
    price: null,
    description: null,
    userId: null,
    username: null,
    information: null,
    classId: null,
    goodsType: null,
    store: null,
    sales: null,
    views: null,
    status: null,
    beginTime: null,
    endTime: null,
  },
  rules: {
  }
})

const { queryParams, form, rules } = toRefs(data)

//分类表
let goodsType = ref([])
//进入前先查询分类列表
onMounted(() => {
  seleteType()
})
//查询分类表
function seleteType() {
  listTclassify().then(res => {
    goodsType.value = res.data.filter(item => item.status === "0" && item.parentId !== 0)
    console.log(goodsType.value);

  })
}

//判断是否有该用户
function exit() {
  getUsers(form.value.userId).then(res => {
    if (res.data === undefined) {
      proxy.$modal.msgError("用户不存在")
      form.value.userId = ""
    }
  })
}

/** 查询商品列表 */
function getList() {
  loading.value = true
  listGoods(queryParams.value).then(response => {
    goodsList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    goodsId: null,
    goodsName: null,
    images: null,
    price: null,
    description: null,
    userId: null,
    information: null,
    classId: null,
    store: null,
    sales: null,
    views: null,
    status: null,
    /*createTime: null,
    updateTime: null*/
  }
  proxy.resetForm("goodsRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  console.log(dateRange.value)
  // 设置日期范围参数
  if (dateRange.value && dateRange.value.length === 2) {
    queryParams.value.beginTime = dateRange.value[0];
    queryParams.value.endTime = `${dateRange.value[1]} 23:59:59`;
  } else {
    queryParams.value.beginTime = null;
    queryParams.value.endTime = null;
  }
  console.log(queryParams.value)
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = []
  // 重置日期参数
  queryParams.value.beginTime = null
  queryParams.value.endTime = null
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.goodsId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加商品"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _goodsId = row.goodsId || ids.value
  getGoods(_goodsId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改商品"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["goodsRef"].validate(valid => {
    if (valid) {
      if (form.value.goodsId != null) {
        updateGoods(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addGoods(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _goodsIds = row.goodsId || ids.value
  proxy.$modal.confirm('是否确认删除商品编号为"' + _goodsIds + '"的数据项？').then(function () {
    return delGoods(_goodsIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => { })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('goods/goods/export', {
    ...queryParams.value
  }, `goods_${new Date().getTime()}.xlsx`)
}

getList()
</script>
